/*
 Copyright (c) 2012, The Cinder Project
 All rights reserved.
 
 This code is designed for use with the Cinder C++ library, http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/


#include "boost/algorithm/string.hpp"
#include "json/json.h"

#include "cinder/Url.h"
#include "cinder/Utilities.h"

#include "Json.h"

using namespace std;

namespace cinder {

JsonTree::JsonTree()
{
	init( "", Json::Value( Json::nullValue ) );
}

JsonTree::JsonTree( const JsonTree &jsonTree )
{
	mChildren = jsonTree.mChildren;
	mKey = jsonTree.mKey;
	mParent = jsonTree.mParent;
	mNodeType = jsonTree.mNodeType;
	mValue = jsonTree.mValue;
	mValueType = jsonTree.mValueType;
}

JsonTree& JsonTree::operator=( const JsonTree &jsonTree )
{
	mChildren = jsonTree.mChildren;
	mKey = jsonTree.mKey;
	mParent = jsonTree.mParent;
	mNodeType = jsonTree.mNodeType;
	mValue = jsonTree.mValue;
	mValueType = jsonTree.mValueType;
	return *this;
}

JsonTree::JsonTree( DataSourceRef dataSource )
{
    
	string jsonString = loadString( dataSource );
	Json::Value value = deserialize( jsonString );
	if ( value.isNull() ) {
		throw ExcJsonParserError();
	}
	init( "", value, true, NODE_OBJECT );

}

JsonTree::JsonTree( const Json::Value &value )
{
	init( "", value, true );
}

JsonTree::JsonTree( const std::string &key, const Json::Value &value )
{
	init( key, value, true, NODE_VALUE );
}
    
JsonTree::JsonTree( const std::string &key )
{
    init( key, Json::Value( Json::nullValue ), NODE_NULL );
}
    
JsonTree::JsonTree( const string &key, const bool &value )
{
    init( key, Json::Value( value ), false, NODE_VALUE, VALUE_BOOL );
}
    
JsonTree::JsonTree( const string &key, const double &value )
{
    init( key, Json::Value( value ), false, NODE_VALUE, VALUE_DOUBLE );
}
    
JsonTree::JsonTree( const string &key, const float &value )
{
    init( key, Json::Value( (double)value ), false, NODE_VALUE, VALUE_DOUBLE );
}

JsonTree::JsonTree( const string &key, const int &value )
{
    init( key, Json::Value( value ), false, NODE_VALUE, VALUE_INT );
}
    
JsonTree::JsonTree( const string &key, const std::string &value )
{
    init( key, Json::Value( value ), false, NODE_VALUE, VALUE_STRING );       
}
    
JsonTree::JsonTree( const string &key, const unsigned int &value )
{
    init( key, Json::Value( value ), false, NODE_VALUE, VALUE_UINT );
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

JsonTree JsonTree::createDoc() 
{
	return JsonTree( Json::Value( Json::objectValue ) ); 
}

void JsonTree::init( const string &key, const Json::Value &value, bool setType, NodeType nodeType, ValueType valueType )
{
	
    mKey = key;
	mNodeType = nodeType;
	mParent = 0;
	mValue = "";
	mValueType = valueType;
    
    if ( !value.isNull() && ( value.isArray() || value.isObject() ) ) {
        
        if ( value.isArray() ) {
            mNodeType = NODE_ARRAY;
            for ( uint32_t i = 0; i < value.size(); i++ ) {
				JsonTree json( toString( i ), value[ i ] );
                push_back( json );
            }
        } else if ( value.isObject() ) {
            mNodeType = NODE_OBJECT;
            Json::Value::Members members = value.getMemberNames();
            for ( Json::Value::Members::const_iterator memberIt = members.begin(); memberIt != members.end(); ++memberIt ) {
				string key = *memberIt;
				JsonTree json( key, value[ key ] );
                push_back( json );
            }
        }
        
    } else {

		if ( value.isBool() ) {
			mValue = toString( value.asBool() );
			if ( setType ) {
				mValueType = VALUE_BOOL;
			}
		} else if ( value.isDouble() ) { 
			mValue = toString( value.asDouble() );
			if ( setType ) {
				mValueType = VALUE_DOUBLE;
			}
		} else if ( value.isInt() ) { 
			mValue = toString( value.asInt() );
			if ( setType ) {
				mValueType = VALUE_INT;
			}
		} else if ( value.isString() ) { 
			mValue = toString( value.asString() );
			if ( setType ) {
				mValueType = VALUE_STRING;
			}
		} else if ( value.isUInt() ) { 
			mValue = toString( value.asUInt() );
			if ( setType ) {
				mValueType = VALUE_UINT;
			}
		}
	
	}
    
}

JsonTree JsonTree::parseJson( const std::string &jsonString )
{
	return JsonTree( "", deserialize( jsonString ) );
}

void JsonTree::push_back( const JsonTree &newChild )
{
	mNodeType = NODE_OBJECT;
	if ( newChild.getKey() == "" ) {
		mNodeType = NODE_ARRAY;
	}
	mChildren.push_back( newChild );
	mChildren.back().mParent = this;
    mValue = "";
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

void JsonTree::setValue( const std::string &value )
{
	mChildren.clear();
	mNodeType = NODE_VALUE;
	mValue = value;
}

void JsonTree::setValueType( ValueType valueType )
{
	mChildren.clear();
	mNodeType = NODE_VALUE;
	mValueType = valueType;
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

JsonTree& JsonTree::operator[]( const std::string &relativePath )
{
	return getChild( relativePath );
}

const JsonTree&	JsonTree::operator[]( const std::string &relativePath ) const
{
	return getChild( relativePath );
}

JsonTree& JsonTree::operator[]( uint32_t index )
{
	return getChild( index );
}

const JsonTree&	JsonTree::operator[]( uint32_t index ) const
{
	return getChild( index );
}

JsonTree::Iter JsonTree::begin() 
{ 
	return mChildren.begin(); 
}

JsonTree::ConstIter JsonTree::begin() const 
{ 
	return mChildren.begin();
}

JsonTree::Iter JsonTree::end() 
{ 
	return mChildren.end();
}

JsonTree::ConstIter JsonTree::end() const 
{ 
	return mChildren.end(); 
}

JsonTree& JsonTree::getChild( const std::string &relativePath, bool caseSensitive, char separator ) 
{
	JsonTree *child = getNodePtr( relativePath, caseSensitive, separator );
	if ( child ) {
		return *child;
	} else {
		throw ExcChildNotFound( *this, relativePath );
	}
}

const JsonTree& JsonTree::getChild( const std::string &relativePath, bool caseSensitive, char separator ) const 
{
	JsonTree *child = getNodePtr( relativePath, caseSensitive, separator );
	if ( child ) {
		return *child;
	} else {
		throw ExcChildNotFound( *this, relativePath );
	}
}

JsonTree& JsonTree::getChild( uint32_t index ) 
{
	JsonTree *child = getNodePtr( toString( index ), false, '.' );
	if ( child ) {
		return *child;
	} else {
		throw ExcChildNotFound( *this, toString( index ) );
	}
}

const JsonTree& JsonTree::getChild( uint32_t index ) const 
{
	JsonTree *child = getNodePtr( toString( index ), false, '.' );
	if ( child ) {
		return *child;
	} else {
		throw ExcChildNotFound( *this, toString( index ) );
	}
}

vector<JsonTree>& JsonTree::getChildren() 
{ 
	return mChildren; 
}

const vector<JsonTree>& JsonTree::getChildren() const 
{ 
	return mChildren; 
}

string& JsonTree::getKey() 
{ 
	return mKey;
}
const string& JsonTree::getKey() const 
{ 
	return mKey;
}

string JsonTree::getPath( char separator ) const
{
	string result;

	const JsonTree *node = this;
	while ( node != 0 ) {
		string nodeName = node->mKey;
		if ( node != this ) {
			nodeName += separator;
		}
		result = nodeName + result;
		node = node->mParent;
	}

	// TO DO -- convert indexes from ".n" to "[n]"

	return result;
}

JsonTree::NodeType& JsonTree::getNodeType()
{
	return mNodeType;
}
const JsonTree::NodeType& JsonTree::getNodeType() const
{
	return mNodeType;
}

JsonTree::ValueType& JsonTree::getValueType()
{
	return mValueType;
}
const JsonTree::ValueType& JsonTree::getValueType() const
{
	return mValueType;
}

//! Returns true if node has child at the specified path
bool JsonTree::hasChild( const string &relativePath, bool caseSensitive, char separator )
{
	return getNodePtr( relativePath, caseSensitive, separator ) != 0;
}
//! Returns true if node has child at the specified path
bool JsonTree::hasChild( const string &relativePath, bool caseSensitive, char separator ) const
{
	return getNodePtr( relativePath, caseSensitive, separator ) != 0;
}

//! Returns true if node has children
bool JsonTree::hasChildren()
{
	return mChildren.size() > 0;
}
//! Returns true if node has children
bool JsonTree::hasChildren() const
{
	return mChildren.size() > 0;
}

JsonTree& JsonTree::getParent() 
{ 
	return *mParent; 
}
const JsonTree& JsonTree::getParent() const 
{ 
	return *mParent;
}
bool JsonTree::hasParent() 
{ 
	return mParent != 0; 
}
bool JsonTree::hasParent() const 
{ 
	return mParent != 0; 
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

//! Find pointer to node at specified path
JsonTree* JsonTree::getNodePtr( const string &relativePath, bool caseSensitive, char separator ) const
{

    // Format path into dotted address
	std::string path = boost::replace_all_copy( relativePath, "[", std::string( 1, separator ) );
	path = boost::replace_all_copy( path, "'", "");
	path = boost::replace_all_copy( path, "]", "");

    // Start search from this node
	JsonTree *curNode = const_cast<JsonTree*>( this );
    
    // Split address at dot and iterate tokens
	vector<string> pathComponents = split( path, separator );
	for ( vector<string>::const_iterator pathIt = pathComponents.begin(); pathIt != pathComponents.end(); ++pathIt ) {

        // Declare target node
		ConstIter node;

        // The key is numeric
		if ( isIndex( *pathIt ) ) {

            // Find child which uses this index as its key
			uint32_t index = boost::lexical_cast<int32_t>( *pathIt );
			uint32_t i = 0;
			for ( node = curNode->getChildren().begin(); node != curNode->getChildren().end(); ++node, i++ ) {
				if ( i == index ) {
					break;
				}
			}

		} else {
			
            // Iterate children
            node = curNode->getChildren().begin();
            while ( node != curNode->getChildren().end() ) {
                
                // Compare child's key to path component
                bool keysMatch = false;
                string key1 = node->getKey();
                string key2 = *pathIt;
                if ( caseSensitive && key1 == key2 ) {
                    keysMatch = true;
                } else if ( !caseSensitive && ( boost::iequals( key1, key2 ) ) ) {
                    keysMatch = true;
                }
                
                // Break if found, advance node if not
                if ( keysMatch ) {
                    break;
                } else {
                    ++node;
                }
                
            }
            
		}

        // Return null pointer if we're out of nodes to search, 
        // otherwise assign node and continue to search its children
		if ( node == curNode->getChildren().end() ) {
            return 0;
        } else {
			curNode = const_cast<JsonTree*>( &( *node ) );
        }

	}

    // Return child
	return curNode;

}

//! Checks if key is numeric
bool JsonTree::isIndex( const string &key )
{
	char* to_convert = const_cast<char *>( key.c_str() );
	char* p = to_convert;
	errno = 0;
	unsigned long val = strtoul( to_convert, &p, 10 );
    if ( val > 0L ) {
        // Prevents "unused variable" warning 
    }
	return !( errno != 0 || to_convert == p || *p != 0 );
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

//! Creates a JsonCpp object from this JsonTree
Json::Value JsonTree::createNativeDoc() const
{
    
    // Check if key is numeric.  If so, use index instead of string key.
    int32_t index = -1;
    if ( isIndex( mKey ) ) {
        index = fromString<int32_t>( mKey );
    }

	// Create JsonCpp value
	Json::Value value( Json::nullValue );

	// Must be declared outside of switch
    uint32_t i = 0;

	// Key on node type
    switch ( mNodeType ) {
    case NODE_ARRAY:

		// Add children to array as objects
        i = 0;
		if ( index >= 0 ) {
			for ( ConstIter childIt = mChildren.begin(); childIt != mChildren.end(); ++childIt, i++ ) {
				value[ index ][ i ] = childIt->createNativeDoc();
			}
		} else {
			for ( ConstIter childIt = mChildren.begin(); childIt != mChildren.end(); ++childIt, i++ ) {
				value[ mKey ][ i ] = childIt->createNativeDoc();
			}
		}

        break;
	case NODE_OBJECT:

		// Add children as value members
		for ( ConstIter childIt = mChildren.begin(); childIt != mChildren.end(); ++childIt ) {
			value[ childIt->getKey() ] = childIt->createNativeDoc();
		}

		break;
	case NODE_VALUE:

		// Set value with native data type
		switch ( mValueType ) {
		case VALUE_BOOL:
			value = Json::Value( fromString<bool>( mValue ) );
			break;
		case VALUE_DOUBLE:
			value = Json::Value( fromString<double>( mValue ) );
			break;
		case VALUE_INT:
			value = Json::Value( fromString<int32_t>( mValue ) );
			break;
		case VALUE_STRING:
			value = Json::Value( mValue );
			break;
		case VALUE_UINT:
			value = Json::Value( fromString<uint32_t>( mValue ) );
			break;
		}

		break;
    default:
        break;
    }

	// Return JsonCpp object
	return value;

}

//! Converts a JSON string into a JsonCpp object
Json::Value JsonTree::deserialize( const string &jsonString )
{
	try {
		Json::Reader reader;
		Json::Value value;
		reader.parse( jsonString, value );
		return value;
	} catch ( ... ) {
		throw ExcJsonParserError();
	}
}

//! Converts a JsonCpp object into a JSON string
string JsonTree::serialize( const Json::Value & value )
{	
	try {
		Json::StyledWriter writer;
		return writer.write( value );
	} catch ( ... ) {
		throw ExcJsonParserError();
	}
}

//! Saves JsonTree to specified path
void JsonTree::write( const fs::path &path, bool createDocument )
{
	write( writeFile( path ), createDocument );
}

//! Saves JsonTree to file
void JsonTree::write( DataTargetRef target, bool createDocument )
{

	// Declare output string
	string jsonString = "";

	try {
		
		// Create JsonCpp data to send to parser
		Json::Value value;
		if ( createDocument ) {
			value = Json::Value( Json::objectValue );
			value.append( createNativeDoc() );
		} else {
			value = createNativeDoc();
		}

		// This routine serializes JsonCpp data and formats it
		Json::StyledWriter writer;
		jsonString = writer.write( value.toStyledString() );
		boost::replace_all( jsonString, "\\n", "\r\n" );
		boost::replace_all( jsonString, "\\\"", "\"" );
		if ( jsonString.length() >= 3 ) {
			jsonString = jsonString.substr( 1, boost::trim_copy( jsonString ).length() - 2 );
		}
		jsonString += "\0";

	} catch ( ... ) {
		throw ExcJsonParserError();
	}

	// Save data to file
	OStreamRef os = target->getStream();
	os->writeData( jsonString.c_str(), jsonString.length() );

}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

JsonTree::ExcChildNotFound::ExcChildNotFound( const JsonTree &node, const string &childPath ) throw()
{
	sprintf( mMessage, "Could not find child: %s for node: %s", childPath.c_str(), node.getPath().c_str() );
}

JsonTree::ExcNonConvertible::ExcNonConvertible( const JsonTree &node ) throw()
{
	sprintf( mMessage, "Unable to convert value for node: %s", node.getPath().c_str() );
}

/////////////////////////////////////////////////////////////////////////////////////////////////////////////

ostream& operator<<( ostream &out, const JsonTree &json )
{
	string doc = JsonTree::serialize( json.createNativeDoc() );
	out << doc;
	return out;
}

} // namespace cinder
